package dev.hax.commandwatch

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.SystemClock
import android.util.Log
import androidx.core.app.NotificationCompat
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.*

class WatchService : Service() {
    companion object {
        const val TAG = "WatchService"
        const val ACTION_LOCATION_CHANGE = "dev.hax.commandwatch.new"

        private const val CHANNEL_ID = "watch_cch"
        private const val SERVICE_ID = 8571
    }

    // -- properties --
    private val timer = Timer()

    private var serviceStarted = false
    private var id: String? = null
    private var server: String? = null
    private var port: String? = null

    // -- override --
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        createChannel()

        getMainActivityClass()?.let {
            val intent = Intent(this, it)
            val pendingIntent = PendingIntent.getActivity(
                this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT
            )

            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setOngoing(true)
                .setContentText("应用运行中")
                .setContentIntent(pendingIntent)
                .setSmallIcon(resources.getIdentifier("ic_launcher", "mipmap", packageName))
                .build()

            startForeground(SERVICE_ID, notification)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (!serviceStarted) {
            serviceStarted = true
            id = intent?.getStringExtra("id")
            server = intent?.getStringExtra("server")
            port = intent?.getStringExtra("port")

            timer.schedule(object : TimerTask() {
                override fun run() {
                    Thread {
                        val httpUrl = "http://$server:$port/api/order/get?key=$id".toHttpUrl()
                        val request = Request.Builder()
                            .url(httpUrl)
                            .build()

                        try {
                            val client = OkHttpClient()
                            val response = client.newCall(request).execute()
                            val str = response.body?.string()
                            str?.let {
                                val json = JSONObject(str)
                                if (json.has("order")) {
                                    val open = json.getJSONObject("order").getString("open")
                                    val foreignApp = packageManager.getLaunchIntentForPackage(open)
                                    foreignApp?.let {
                                        it.flags =
                                            Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
                                        startActivity(it)
                                    }
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }.start()
                }
            }, 0, 500)
        }

        return START_NOT_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
        stopForeground(true)
    }

    // -- private --
    private fun createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "command-watch-helper"
            val channel = NotificationChannel(
                CHANNEL_ID,
                name,
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                setSound(null, null)
            }
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
        }
    }

    private fun getMainActivityClass(): Class<*>? {
        val context = applicationContext
        val packageName = context.packageName
        val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName)
        val className = launchIntent?.component?.className ?: return null

        return try {
            Class.forName(className)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
            null
        }
    }
}